<?php

namespace app\home\controller;

use app\common\controller\Home;

class Pay extends Home
{
    protected $NoNeedLogin = ['callback', 'notice'];

    protected $BusinessModel = null;
    protected $PayModel = null;
    protected $OrderModel = null;
    protected $RecordModel = null;
    protected $ReceiveModel = null;
    protected $SubjectModel = null;
    protected $CommissionModel = null;

    public function __construct()
    {
        parent::__construct();

        $this->OrderModel = model('subject.Order');
        $this->ReceiveModel = model('coupon.Receive');
        $this->RecordModel = model('business.Record');
        $this->CommissionModel = model('business.Commission');
        $this->BusinessModel = model('business.Business');
        $this->SubjectModel = model('subject.Subject');
        $this->PayModel = model('pay.Pay');
    }

    public function callback()
    {
        if ($this->request->isPost()) {
            $params = $this->request->param();

            // 获取订单的id
            $payid = $params['id'] ?? 0;

            $pay = $this->PayModel->where(['status' => '1'])->find($payid);

            if (!$pay) {
                $this->error('支付订单不存在');
            }

            // 获取订单支付金额
            $price = $pay['price'] ?? 0;

            // 转成浮点数
            $price = floatval($price);

            if ($price <= 0) {
                $this->error('订单金额不能为0元');
            }

            // 获取携带参数
            $third = $pay['third'] ?? '';

            $thirdArr = json_decode($third, true);

            $busid = $thirdArr['busid'] ?? 0;
            $subid = $thirdArr['subid'] ?? 0;
            $couponid = $thirdArr['coupon'] ?? 0;

            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
            }

            $subject = $this->SubjectModel->find($subid);

            if (!$subject) {
                $this->error('课程不存在');
            }

            $pay_type = $pay['paytype'];

            $payment = '';

            switch ($pay_type) {
                case 0:
                    $payment = '微信支付';
                    break;
                case 1:
                    $payment = '支付宝支付';
                    break;
            }

            /* 
                新增订单记录
                新增消费记录
                更改优惠券状态
                新增佣金记录
            */

            // 开启事务
            $this->OrderModel->startTrans();
            $this->RecordModel->startTrans();
            $this->ReceiveModel->startTrans();
            $this->CommissionModel->startTrans();

            // 封装订单数据
            $OrderData = [
                'subid' => $subid, // 课程id
                'busid' => $busid, // 用户id
                'total' => $price,
                'code' => build_code('ST')
            ];

            // 插入数据表
            $OrderStatus = $this->OrderModel->validate('common/subject/Order')->save($OrderData);

            if ($OrderStatus === false) {
                $this->error($this->OrderModel->getError());
            }

            // 组装用户消费记录数据
            $RecordData = [
                'total' => "-{$price}",
                'content' => "购买课程：【{$subject['title']}】{$payment}支付了 {$price} 元",
                'busid' => $busid
            ];

            // 插入数据
            $RecordStatus = $this->RecordModel->validate('common/business/Record')->save($RecordData);

            if ($RecordStatus === false) {
                $this->OrderModel->rollback();
                $this->error($this->RecordModel->getError());
            }

            $receive = $this->ReceiveModel->with(['coupon'])->where(['receive.status' => '1'])->find($couponid);

            // 更新优惠券状态
            if ($receive) {
                $ReceiveData = [
                    'id' => $receive['id'],
                    'status' => 0
                ];

                $ReceiveStatus = $this->ReceiveModel->isUpdate(true)->save($ReceiveData);

                if ($ReceiveStatus === false) {
                    $this->OrderModel->rollback();
                    $this->RecordModel->rollback();

                    $this->error('更新优惠券状态失败');
                }
            }

            // 佣金记录
            $parentid = $business['parentid'] ?? 0;

            $parent = $this->BusinessModel->find($parentid);

            if ($parent) {
                $AmountRate = config('site.AmountRate');

                // 组装佣金记录
                $CommissionData = [
                    'orderid' => $this->OrderModel->id,
                    'busid' => $this->auth->id,
                    'parentid' => $parentid,
                    'amount' => bcmul($price, $AmountRate),
                    'type' => 'subject',
                    'status' => 0,
                ];

                $CommissionStatus = $this->CommissionModel->validate('common/business/Commission')->save($CommissionData);

                if ($CommissionStatus === false) {
                    $this->OrderModel->rollback();
                    $this->RecordModel->rollback();
                    $this->ReceiveModel->rollback();

                    $this->error($this->CommissionModel->getError());
                }
            }

            if ($OrderStatus === false || $RecordStatus === false) {
                $this->OrderModel->rollback();
                $this->RecordModel->rollback();
                $this->ReceiveModel->rollback();
                $this->CommissionModel->rollback();

                $this->error('支付失败');
            } else {
                $this->OrderModel->commit();
                $this->RecordModel->commit();
                $this->ReceiveModel->commit();
                $this->CommissionModel->commit();

                $this->success('支付成功');
            }
        }
    }

    public function notice()
    {
        $subid = $this->request->param('subid',0,'trim');

        return $this->success('支付成功', url('/home/index/collect',['subject' => $subid]));
    }
}
